package Action;

import Entities.UserEntity;
import Service.RecommendService;
import Service.UpdateInfoService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

//修改用户信息的Action
public class UpdateInfoAction extends ActionSupport
{
    private String user_name;
    private String user_password;
    private String surePassword;
    private String user_tag1;
    private String user_tag2;
    private String user_tag3;
    private String user_tag4;
    private String user_tag5;
    private String user_tag6;
    private String selectCount = "0";  //选择标签的个数
    private UpdateInfoService updateInfoService;
    private String page = "0";
    private int limit = 15;
    private String tag_register = "0";  //若为0则表示是重新选择标签页面过来的；若为1则表示是注册的选择标签页面过来的
    private String whichPanel = "1";  //用于表示跳转回主页时跳到哪个Panel

    public String getSelectCount() {
        return selectCount;
    }

    public void setSelectCount(String selectCount) {
        this.selectCount = selectCount;
    }

    private String [] tagsForShow;

    public String[] getTagsForShow() {
        return tagsForShow;
    }

    public void setTagsForShow(String[] tagsForShow) {
        this.tagsForShow = tagsForShow;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_password() {
        return user_password;
    }

    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }

    public String getSurePassword() {
        return surePassword;
    }

    public void setSurePassword(String surePassword) {
        this.surePassword = surePassword;
    }

    public String getUser_tag1() {
        return user_tag1;
    }

    public void setUser_tag1(String user_tag1) {
        this.user_tag1 = user_tag1;
    }

    public String getUser_tag2() {
        return user_tag2;
    }

    public void setUser_tag2(String user_tag2) {
        this.user_tag2 = user_tag2;
    }

    public String getUser_tag3() {
        return user_tag3;
    }

    public void setUser_tag3(String user_tag3) {
        this.user_tag3 = user_tag3;
    }

    public String getUser_tag4() {
        return user_tag4;
    }

    public void setUser_tag4(String user_tag4) {
        this.user_tag4 = user_tag4;
    }

    public String getUser_tag5() {
        return user_tag5;
    }

    public void setUser_tag5(String user_tag5) {
        this.user_tag5 = user_tag5;
    }

    public String getUser_tag6() {
        return user_tag6;
    }

    public void setUser_tag6(String user_tag6) {
        this.user_tag6 = user_tag6;
    }

    public UpdateInfoService getUpdateInfoService() {
        return updateInfoService;
    }

    public void setUpdateInfoService(UpdateInfoService updateInfoService) {
        this.updateInfoService = updateInfoService;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public String getTag_register() {
        return tag_register;
    }

    public void setTag_register(String tag_register) {
        this.tag_register = tag_register;
    }

    public String getWhichPanel() {
        return whichPanel;
    }

    public void setWhichPanel(String whichPanel) {
        this.whichPanel = whichPanel;
    }

    //返回用户信息（用于修改用户信息界面）
    public String returnUserInfo()
    {
        Map<String, Object> session =  (Map<String, Object>) ActionContext.getContext().getSession();
        String user_name = (String) session.get("user_name");  //获取登录或注册时存入session的参数——用户名

        session.remove("passwordChange");
        session.remove("tagChange");
        UserEntity ue = updateInfoService.returnUserInfo(user_name);
        if(ue==null)
            return "fail";

        String[] tagList = new String[6];
        tagList[0] = ue.getUserTag1();
        tagList[1] = ue.getUserTag2();
        tagList[2] = ue.getUserTag3();
        tagList[3] = ue.getUserTag4();
        tagList[4] = ue.getUserTag5();
        tagList[5] = ue.getUserTag6();
        session.put("tagList",tagList);
        return "success";
    }

    //修改用户密码(updatePasswordAction)
    public String updatePassword()
    {
        Map<String, Object> session =  (Map<String, Object>) ActionContext.getContext().getSession();
        String user_name = (String) session.get("user_name");  //获取登录或注册时存入session的参数——用户名
        String user_password = this.getUser_password();  //用户输入的修改后的密码
        String surePassword = this.getSurePassword();  //确认的密码
        if(user_password.isEmpty()||surePassword.isEmpty())
        {
            this.addFieldError("passwordUpdateResult", "不能提交空密码！");
            return "fail";
        }
        if(!user_password.equals(surePassword))
        {
            //提示两次输入的密码不一致

        }
        boolean flag = updateInfoService.updatePassword(user_name, user_password);
        if(flag == true)
        {
            setWhichPanel("3");

            //从缓存中读取推荐列表并传给前端
            Cache recommendResultCache = CacheManager.getCacheManager("__DEFAULT__").getCache("RecommendResultCache");
            Element resultElement = recommendResultCache.get(user_name+ " recommendResult");
            List<String> recommendResult = (List<String>) resultElement.getObjectValue();
            session.put("recommendList", recommendResult);

            return "success";
        }
        else
            return "fail";
    }

    private String[] subArray(String[] array,int start,int end){
        if (start >= array.length) {
            String [] shit = new String[1];
            shit[0] = "NO_MORE";
            return shit;
        }
        String [] res = new String [end-start+1];
        for (int i = start;i<=end;i++){
            res[i-start] = array[i];
        }
        return res;

    }

    //修改用户标签(updateTagAction)
    public String updateTag()
    {
        //前端已经保证用户选择的标签数目为[ 1 , 6 ]，选择的标签数储存在selectCount中
        boolean flag;
        Map<String, Object> session =  (Map<String, Object>)ActionContext.getContext().getSession();
        String user_name = (String) session.get("user_name");  //获取注册时存入session的参数——用户名
        UserEntity ue = new UserEntity();
        ue.setUserName(user_name);
        ue.setUserTag1(Integer.parseInt(selectCount) >= 1?user_tag1:null);
        ue.setUserTag2(Integer.parseInt(selectCount) >= 2?user_tag2:null);
        ue.setUserTag3(Integer.parseInt(selectCount) >= 3?user_tag3:null);
        ue.setUserTag4(Integer.parseInt(selectCount) >= 4?user_tag4:null);
        ue.setUserTag5(Integer.parseInt(selectCount) >= 5?user_tag5:null);
        ue.setUserTag6(Integer.parseInt(selectCount) >= 6?user_tag6:null);
        ue.setTagMark1(0);
        ue.setTagMark2(0);
        ue.setTagMark3(0);
        ue.setTagMark4(0);
        ue.setTagMark5(0);
        ue.setTagMark6(0);
        flag = updateInfoService.updateTag(ue);
        if(flag == true)
        {
            String[] tagList = new String[6];
            tagList[0] = ue.getUserTag1()==null?ue.getUserTag1():"null";
            tagList[1] = ue.getUserTag2()==null?ue.getUserTag2():"null";
            tagList[2] = ue.getUserTag3()==null?ue.getUserTag3():"null";
            tagList[3] = ue.getUserTag4()==null?ue.getUserTag4():"null";
            tagList[4] = ue.getUserTag5()==null?ue.getUserTag5():"null";
            tagList[5] = ue.getUserTag6()==null?ue.getUserTag6():"null";
            session.put("tagList",tagList);
            session.put("tagChange","用户标签修改成功！");

            if(Integer.parseInt(tag_register) != 1)  //表示用户不是初次选择标签，则直接跳转到homeAction就可以了
                //若是用户修改标签成功，应先立即更新推荐列表，再返回到main.jsp
                refreshRecommendList();

            if(Integer.parseInt(tag_register) != 1)
                setWhichPanel("3");
            return "success";
        }
        else
            return "fail";
    }

    //更新推荐列表（用户重新选择标签成功时调用）
    public void refreshRecommendList()
    {
        RecommendService recommendService = (RecommendService) WebApplicationContextUtils.getWebApplicationContext
                (ServletActionContext.getServletContext()).getBean("recommendService");
        recommendService.refreshRecommend();
    }

    public String execute()
    {
        Map<String, Object> session =  (Map<String, Object>) ActionContext.getContext().getSession();
        String user_name = (String) session.get("user_name");  //获取登录或注册时存入session的参数——用户名

        UserEntity ue = new UserEntity();
        ue.setUserName(user_name);
        ue.setUserPassword(user_password);
        ue.setUserTag1(user_tag1);
        ue.setUserTag2(user_tag2);
        ue.setUserTag3(user_tag3);
        ue.setUserTag4(user_tag4);
        ue.setUserTag5(user_tag5);
        ue.setUserTag6(user_tag6);
        boolean flag = updateInfoService.update(ue);

        if(flag == true)
        {
            this.addFieldError("update","更新用户信息成功！");
            return "success";
        }
        else
        {
            this.addFieldError("update","更新用户信息失败！");
            return "success";
        }
    }

}
